package workers;

import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;

import model.Software;
import workerUIs.StepFrame;
import workflow.IEventListener;
import workflow.SoftwareDevelopmentWorkflow;
import workflow.TestEvent;
import workflow.WorkflowEvent.EventType;

public class TestStepWorker extends AbstractStepSwingWorker {

	private final BlockingQueue<Software> outputRelease;
	private StepFrame nextFrameRelease;
	private boolean testOk = false;

	public TestStepWorker(StepFrame frame, BlockingQueue<Software> inputQueue, BlockingQueue<Software> outputRepair, BlockingQueue<Software> outputRelease, StepFrame repairFrame, StepFrame releaseFrame, boolean testOk, final IEventListener listener) {
		super(frame, inputQueue, outputRepair, repairFrame, listener);
		this.outputRelease = outputRelease;
		this.nextFrameRelease = releaseFrame;
		this.testOk = testOk;
	}

	@Override
	protected Software doInBackground() throws Exception {
		try {
			this.software = this.inputQueue.take();
			if (listener != null) listener.onEvent(TestEvent.createEvent(this.software.getId(), getTaskName(), EventType.START, testOk));
			Thread.sleep(delay);
			if (this.testOk) {
				this.outputRelease.put(this.software);
			} else {
				this.outputQueue.put(this.software);
			}
			if (listener != null) listener.onEvent(TestEvent.createEvent(this.software.getId(), getTaskName(), EventType.END, testOk));
			return this.software;			
		} catch (Exception e) {
			e.printStackTrace();
			logger.log(Level.SEVERE, "Exception when executing step: " + getClass().getName() + ": " + e.getMessage());
		}
		return null;
	}
	
	@Override
	protected Software doStep(Software software) {
		return software;
	}
	
	@Override
	protected String getTaskName() {
		return "test";
	}
	
	@Override
	protected void done() {
		if (this.inputQueue != null && inputQueue.isEmpty()) {
			getFrame().getNextButton().setEnabled(false);
		}
		String previousStepString = this.frame.getTextArea().getText();
		if (this.software != null) {
			this.frame.getTextArea().setText(previousStepString + "\n--------------\n" + this.software.toString());
		} else {
			this.frame.getTextArea().setText(previousStepString + "\n--------------\n" + "Software NULL!");
		}
		if (this.testOk) {
			this.nextFrameRelease.getNextButton().setEnabled(true);
			if (SoftwareDevelopmentWorkflow.automaticMode) {
				this.nextFrameRelease.getNextButton().doClick();
			}
		} else {
			this.nextFrame.getNextButton().setEnabled(true);
			if (SoftwareDevelopmentWorkflow.automaticMode) {
				this.nextFrame.getNextButton().doClick();
			}
		}
	}

}
